package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.Task;
import cn.stylefeng.guns.sys.modular.system.entity.TaskFlow;
import cn.stylefeng.guns.sys.modular.system.entity.TaskStatus;
import cn.stylefeng.guns.sys.modular.system.mapper.TaskFlowMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.TaskMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskParam;
import cn.stylefeng.guns.sys.modular.system.model.result.TaskResult;
import cn.stylefeng.guns.sys.modular.system.service.TaskService;
import cn.stylefeng.guns.sys.modular.system.service.WeChatSendTempMsgService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-10
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TaskFlowMapper taskFlowMapper;
    //模板消息
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @Override
    public void add(TaskParam param) {
        Task entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(TaskParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(TaskParam param) {
        Task oldEntity = getOldEntity(param);
        Task newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public TaskResult findBySpec(TaskParam param) {
        return null;
    }

    @Override
    public List<TaskResult> findListBySpec(TaskParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(TaskParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(TaskParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Task getOldEntity(TaskParam param) {
        return this.getById(getKey(param));
    }

    private Task getEntity(TaskParam param) {
        Task entity = new Task();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    public List<Integer> listIdsByRole(Long roleid) {
        return baseMapper.listIdsByRole(roleid);
    }

    /**
     * 新增任务信息
     *
     * @param taskStatus
     */
    @Override
    public ResponseData aaa(List<TaskStatus> taskStatus) throws ParseException {

        //修改状态,所有修改操作数据库新增条数必须都大于0才会提交事务
        StringBuilder result = new StringBuilder();
        // 数据库修改条数
        int count = 0;

        if (ToolUtil.isNotEmpty(taskStatus)) {

            for (TaskStatus status : taskStatus) {

                //填写内容为固定项
                if (status.getTaskId() != null) {

                    //查询该工程该项是否已经填写信息
                    int msg = taskMapper.getRent(status.getProId(), status.getTaskId());

                    //之前没有填写过信息
                    if (msg == 0) {
                        status.setStatus(1);//提交信息
                        //新增信息
                        count = taskMapper.addRent(status);
                        result.append(count > 0 ? 1 : 0);

                        //流程明细表
                        TaskFlow taskFlow = new TaskFlow();
                        taskFlow.setProId(status.getProId());
                        taskFlow.setTaskId(status.getTaskId());
                        taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
                        if (status.getTaskName() != null || status.getTaskName() != "") {
                            taskFlow.setTaskName(status.getTaskName());
                        }
//                        taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
//                        taskFlow.setCreateTime(new Date());
                        //新增流程明细表
                        count = taskFlowMapper.add(taskFlow);
                        result.append(count > 0 ? 1 : 0);

                        //开工日期
                        if (status.getTaskId() == 32) {
                            TaskStatus status1 = new TaskStatus();
                            //预估完工日期
                            status1.setTaskId(33);
                            status1.setContent(DateUtil.subMonth(status.getContent()));
                            status1.setProId(status.getProId());
                            status1.setStatus(1);

                            //新增预估完工日期
                            count = taskMapper.addRent(status1);
                            result.append(count > 0 ? 1 : 0);

                            //流程明细表
                            TaskFlow taskFlow1 = new TaskFlow();
                            taskFlow1.setProId(status.getProId());
                            taskFlow1.setTaskId(33);
                            taskFlow1.setStatus(1);//1提交；2审核未通过；3审核通过
                            taskFlow1.setTaskName("预估完工日期");
//                            taskFlow1.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow1.setCreateTime(new Date());
                            //新增流程明细表
                            count = taskFlowMapper.add(taskFlow1);
                            result.append(count > 0 ? 1 : 0);

                            //营业执照
                        } else if (status.getTaskId() == 11) {

                            //////////////////////////
                            //通知可乐机负责人
///////////////////////////


                            TaskStatus status2 = new TaskStatus();
                            //可乐机报备
                            status2.setTaskId(19);
                            status2.setProId(status.getProId());
                            status2.setStatus(1);

                            //新增可乐机报备
                            count = taskMapper.addRent(status2);
                            result.append(count > 0 ? 1 : 0);

                            //流程明细表
                            TaskFlow taskFlow1 = new TaskFlow();
                            taskFlow1.setProId(status.getProId());
                            taskFlow1.setTaskId(19);
                            taskFlow1.setStatus(1);//1提交；2审核未通过；3审核通过
                            taskFlow1.setTaskName("可乐机报备");
//                            taskFlow1.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow1.setCreateTime(new Date());
                            //新增流程明细表
                            count = taskFlowMapper.add(taskFlow1);
                            result.append(count > 0 ? 1 : 0);
                        }
                    }
//                    else {
//                        return ResponseData.error("之前已提交过信息");
//                    }

                    //新增任务内容填写
                } else {
                    if (status.getTaskName() != null) {
                        //查询该任务名称是否存在
                        int name = taskMapper.selectName(status.getTaskName());
                        //名称不存在
                        if (name == 0) {
                            status.setStatus(1);//提交信息
                            //新增信息
                            count = taskMapper.addRent(status);
                            result.append(count > 0 ? 1 : 0);

                            //流程明细表
                            TaskFlow taskFlow = new TaskFlow();
                            taskFlow.setProId(status.getProId());
                            taskFlow.setTaskId(status.getTaskId());
                            taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
                            if (status.getTaskName() != null || status.getTaskName() != "") {
                                taskFlow.setTaskName(status.getTaskName());
                            }
//                            taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow.setCreateTime(new Date());
                            //新增流程明细表
                            count = taskFlowMapper.add(taskFlow);
                            result.append(count > 0 ? 1 : 0);

                        } else {
                            return ResponseData.error("该任务名称已存在");
                        }
                    }

                }

            }
        }
        if (result.indexOf("0") >= 0) {
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseData.error("添加失败");
        }
        return ResponseData.success();

    }

    /**
     * 状态表新增数据
     *
     * @param status
     */
    @Override
    public ResponseData insertRent(TaskStatus status, TaskFlow taskFlow) {

        //修改状态,所有修改操作数据库新增条数必须都大于0才会提交事务
        StringBuilder result = new StringBuilder();
        // 数据库修改条数
        int count = 0;

        count = taskMapper.addRent(status);
        result.append(count > 0 ? 1 : 0);
        count = taskFlowMapper.add(taskFlow);
        result.append(count > 0 ? 1 : 0);

        if (result.indexOf("0") >= 0) {
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseData.error("添加失败");
        }else {
            return ResponseData.success();
        }
    }

    /**
     * 督导工程部页面
     *
     * @param proId
     * @return
     */
    @Override
    public List<TaskStatus> taskList(Integer proId) {
//        //获取当前登陆者id
//        Long userId = LoginContextHolder.getContext().getUserId();
//        //获取当前登陆者角色id
//        String roleId = taskMapper.getRoleId(userId);

        //获取当前登陆者角色id
        List<Long> roleList = LoginContextHolder.getContext().getUser().getRoleList();

        return taskMapper.getList(roleList, proId);
        //return taskMapper.taskList(proId, roleId);
    }

    /**
     * 根据店名查询ProID
     * @param name
     * @return
     */
    @Override
    public int selectProId(String name) {
        return taskMapper.selectProId(name);
    }

    @Override
    public int selectCount(int proId) {
        return taskMapper.select(proId);
    }

    /**
     * 向可乐机负责人推送消息
     *
     * @return
     */
    public String sendMsg() {
        return null;
    }


    /**
     * 新增任务信息
     * @param taskStatus
     * @return
     * @throws ParseException
     */
    @Override
    public ResponseData addRent(List<TaskStatus> taskStatus) throws ParseException {

        //修改状态,所有修改操作数据库新增条数必须都大于0才会提交事务
        StringBuilder result = new StringBuilder();
        // 数据库修改条数
        int count = 0;

        if (ToolUtil.isNotEmpty(taskStatus)) {

            //任务状态
            List<TaskStatus> taskStatuses = new ArrayList<>();
            //任务流水
            List<TaskFlow> taskFlows = new ArrayList<>();

            for (TaskStatus status : taskStatus) {

                //填写内容为固定项
                if (status.getTaskId() != null) {

                    //查询该工程该项是否已经填写信息
                    int msg = taskMapper.getRent(status.getProId(), status.getTaskId());

                    //之前没有填写过信息
                    if (msg == 0) {

                        status.setStatus(1);//提交信息

                        taskStatuses.add(status);

                        //流程明细表
                        TaskFlow taskFlow = new TaskFlow();
                        taskFlow.setProId(status.getProId());
                        taskFlow.setTaskId(status.getTaskId());
                        taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
                        if (status.getTaskName() != null || status.getTaskName() != "") {
                            taskFlow.setTaskName(status.getTaskName());
                        }
                        taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
//                        taskFlow.setCreateTime(new Date());

                        taskFlows.add(taskFlow);

                        //开工日期
                        if (status.getTaskId() == 32) {
                            TaskStatus status1 = new TaskStatus();
                            //预估完工日期
                            status1.setTaskId(33);
                            status1.setContent(DateUtil.subMonth(status.getContent()));
                            status1.setProId(status.getProId());
                            status1.setStatus(1);

                            taskStatuses.add(status1);

                            //流程明细表
                            TaskFlow taskFlow1 = new TaskFlow();
                            taskFlow1.setProId(status.getProId());
                            taskFlow1.setTaskId(33);
                            taskFlow1.setStatus(1);//1提交；2审核未通过；3审核通过
                            taskFlow1.setTaskName("预估完工日期");
//                            taskFlow1.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow1.setCreateTime(new Date());

                            taskFlows.add(taskFlow1);

                            //营业执照
                        } else if (status.getTaskId() == 11) {

                            //////////////////////////
                            //通知可乐机负责人
///////////////////////////
                            Date date = new Date();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            String format = simpleDateFormat.format(date);
                            //查询店名
                            String dm = taskMapper.selectDm(status.getProId());
                            String data = dm + "应入可乐机";

                            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm,null,"可乐机状态","可乐机",format,data);

                            String[] openids = new String[]{"oM18PwWQsdIP3QEKcWejL1tF3X8s"};

                            //推送消息
                            weChatSendTempMsgService.sendmsg(openids,null,tempObj);

                            TaskStatus status2 = new TaskStatus();
                            //可乐机报备
                            status2.setTaskId(19);
                            status2.setProId(status.getProId());
                            status2.setStatus(1);

                            taskStatuses.add(status2);


                            //流程明细表
                            TaskFlow taskFlow1 = new TaskFlow();
                            taskFlow1.setProId(status.getProId());
                            taskFlow1.setTaskId(19);
                            taskFlow1.setStatus(1);//1提交；2审核未通过；3审核通过
                            taskFlow1.setTaskName("可乐机报备");
//                            taskFlow1.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow1.setCreateTime(new Date());

                            taskFlows.add(taskFlow1);
                        }
                    }

                    //新增任务内容填写
                } else {
                    if (status.getTaskName() != null) {
                        //查询该任务名称是否存在
                        int name = taskMapper.selectName(status.getTaskName());
                        //该工程中是否存在此名称
                        int taskName = taskMapper.selectTaskName(status.getTaskName(),status.getProId());
                        //该工程中没有填写此任务
                        if (taskName == 0){
                            //名称不存在
                            if (name == 0) {
                                status.setStatus(1);//提交信息

                                taskStatuses.add(status);

                                //流程明细表
                                TaskFlow taskFlow = new TaskFlow();
                                taskFlow.setProId(status.getProId());
                                taskFlow.setTaskId(status.getTaskId());
                                taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
                                if (status.getTaskName() != null || status.getTaskName() != "") {
                                    taskFlow.setTaskName(status.getTaskName());
                                }
//                            taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
//                            taskFlow.setCreateTime(new Date());

                                taskFlows.add(taskFlow);

                            }
                        }

                    }

                }

            }

            if (taskStatuses.size() != 0){
                //新增信息
                count = taskMapper.addRentList(taskStatuses);
                result.append(count > 0 ? 1 : 0);
            }

            if (taskFlows.size() != 0){
                //新增流程明细表
                count = taskFlowMapper.addList(taskFlows);
                result.append(count > 0 ? 1 : 0);
            }


        }
        if (result.indexOf("0") >= 0) {
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseData.error("添加失败");
        }else {
            return ResponseData.success();
        }


    }

}
